package com.ruoyi.framework.oss;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;


/**
 * @description: 统一 redis 工具类
 * @author: 01437768
 * @create: 2019-10-31 18:10
 **/
@Component
public class AliyunOssClient {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;


    public OSS createOssClient() {
        // 创建OSSClient实例。
        OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
        return ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);
    }

    public OSSObject getFileName(OSS ossClient, String fileName) {
        // 创建OSSClient实例。
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        return ossObject;

    }

    public ObjectMetadata downLoad(OSS ossClient, String objectName, File file) {
        // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        ObjectMetadata object = ossClient.getObject(new GetObjectRequest(bucketName, objectName), file);
        return object;

    }

    public void uplodafile(String path, File file) {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, file);
            // 上传文件。
            client.putObject(putObjectRequest);
        } catch (Exception oe) {
            logger.error(oe.getMessage());
            throw oe;
        } finally {
            client.shutdown();
        }

    }

    public void uplodafile(String path, InputStream inputStream) {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, inputStream);
            // 上传文件。
            client.putObject(putObjectRequest);
        } catch (Exception oe) {
            logger.error(oe.getMessage());
            throw oe;
        } finally {
            client.shutdown();
        }

    }

}
